# Display.py
#
# Copyright (c) 2006 Michael Hobbs
#
# This file is part of iTorrent.
#
# iTorrent is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# iTorrent is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with iTorrent; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


import utils


class Display(object):
	def __init__(self):
		super(Display, self).__init__()
		self.cache = {}
		self.lastDisplay = {}
		self.lastStats = {}

	def startedTorrent(self, torrent, info):
		self.cache[torrent] = info

	def shutdownTorrent(self, torrent):
		# We may get multiple notifications on the same torrent
		if not torrent in self.cache:
			return
		self.lastDisplay[torrent] = self.cache.pop(torrent)
		self.lastStats[torrent] = torrent.get_status(False, True)

	def failedTorrent(self, torrent):
		# We may get multiple failure notifications on the same torrent
		if not torrent in self.cache:
			return
		self.lastDisplay[torrent] = self.cache.pop(torrent)

	def info(self, message, torrent=None):
		self.showMessage('INFO', message, torrent)

	def warning(self, message, torrent=None):
		self.showMessage('WARN', message, torrent)

	def error(self, message, torrent=None):
		self.showMessage('EROR', message, torrent)

	def critical(self, message, torrent=None):
		utils.debugDump()
		message = '\n' \
				'########### A CRITICAL ERROR HAS OCCURRED ###########\n' \
				'Please submit the debug.dump file in your data directory to\n' \
				'http://sourceforge.net/tracker/?func=add&group_id=163841&atid=829332\n' \
				'Also include the URL of the podcast that caused the error, if possible.\n' \
				'#####################################################\n\n'
		self.showMessage('CRIT', message, torrent)

	def showMessage(self, level, message, torrent):
		torrentName = ''
		if torrent and torrent in self.cache:
			torrentName = '%s: ' % self.cache[torrent].metainfo.name
		print '[%s] %s%s' % (level, torrentName, message)

	# TODO: Transform the stats into a YAML doc and use that for display.
	# TODO: Clean this up.
	def status(self):
		if not self.cache and not self.lastDisplay:
			return
		print '[STAT]'
		for torrent in self.cache.keys() + self.lastDisplay.keys():
			if torrent in self.lastDisplay:
				info = self.lastDisplay.pop(torrent)
			else:
				info = self.cache[torrent]
			name = info.metainfo.name
			progress = '0.0%'
			peers = 0
			seeds = 0
			seedsmsg = "S"
			dist = 0.0
			uprate = 0.0
			dnrate = 0.0
			upTotal = 0
			#~ dnamt = 0
			t = 0
			#~ msg = ''
			stats = torrent.get_status(False, True)
			status = stats['activity']
			storageWrapper = torrent._storagewrapper
			#~ dnamt = startSize + stats['downTotal']
			size = storageWrapper.realTotalLength
			dnamt = size - storageWrapper.amount_inactive
			progress = '%.1f%%' % (dnamt*100.0/size)
			#~ progress = '%.1f%%' % (stats['fractionDone'] * 100.0)
			#~ progress = '%.1f%%' % (int(stats['fractionDone']*1000)/10.0)
			#~ if torrent.started and not torrent.closed:
			if not torrent.closed or torrent in self.lastStats:
				s = self.lastStats.pop(torrent, stats)
				dist = s['numCopies']
				if torrent.is_seed:
					seeds = 0 # s['numOldSeeds']
					seedsmsg = "s"
				elif not torrent.closed:
					if s['numSeeds'] + s['numPeers']:
						t = stats['timeEst']
						if t is None:
							t = -1
						if t == 0:  # unlikely
							t = 0.01
						status = _("downloading")
					else:
						t = -1
						status = _("connecting to peers")
					seeds = s['numSeeds']
				dnrate = s['downRate']
				peers = s['numPeers']
				uprate = s['upRate']
				upTotal = s['upTotal']
				#~ dnamt = size - s['files_left'][0]
			#~ if torrent.errors and (torrent.closed or torrent.errors[-1][0] + 300 > time()):
				#~ msg = torrent.errors[-1][2]
			print '%s: %s (%s) - %sP%s%s%.3fD u%0.1fK/s-d%0.1fK/s u%dK-d%dK' % \
					(name, status, progress, peers, seeds, seedsmsg, dist,
					uprate/1000, dnrate/1000, upTotal/1024, dnamt/1024)
		print
		return False

